import frappe

def before_uninstall():
    """EAM卸载前处理：清理ERPNext中的EAM工作空间"""
    print("🧹 开始清理ERPNext中的EAM工作空间...")
    
    try:
        # 查找并删除EAM相关工作空间
        # 清理可能的历史命名残留 + 新命名
        workspaces_to_delete = [
            "EAM_Management",
            "EAM_ERPNext",
            "EAM",
            "eamcopy"
        ]
        
        deleted_count = 0
        for workspace_name in workspaces_to_delete:
            if frappe.db.exists("Workspace", {"name": workspace_name, "app": "erpnext"}):
                try:
                    frappe.delete_doc("Workspace", workspace_name, ignore_permissions=True)
                    deleted_count += 1
                    print(f"✅ 已删除工作空间: {workspace_name}")
                except Exception as e:
                    print(f"⚠️ 删除工作空间 {workspace_name} 失败: {str(e)}")
        
        if deleted_count > 0:
            frappe.db.commit()
            print(f"✅ 共清理了 {deleted_count} 个EAM工作空间")
        else:
            print("ℹ️ 未找到需要清理的EAM工作空间")
            
    except Exception as e:
        print(f"❌ 清理过程中发生错误: {str(e)}")
        frappe.log_error(str(e), "EAM Workspace Cleanup Error")
        # 继续卸载流程，不因清理失败而中断